Page({

  /**
   * 页面的初始数据
   */
  data: {
    schema:[
    ],
    zh: '',
    title:'',
    remark: '',
    webUrl: '',
    formData:{
    },
    result: '',
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })

    this.setData({
      apiType: options.zh,
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  },
  getFormData(e) {
  },
  verifyCopyToChannel(audioBuffer, channelIndex, sourceArray, startInChannel = 0) {
    // 基本参数验证
    // if (!(audioBuffer instanceof AudioBuffer)) {
    //     return { success: false, message: '无效的AudioBuffer实例' };
    // }
  
    // 获取目标声道数据
    const targetData = audioBuffer.getChannelData(channelIndex);
    const maxCheckLength = Math.min(
        sourceArray.length, 
        targetData.length - startInChannel
    );
  
    // 检查不匹配项
    const mismatches = [];
    const sampleTolerance = 1e-6;
  
    for (let i = 0; i < maxCheckLength; i++) {
        const sourceValue = sourceArray[i];
        const targetValue = targetData[startInChannel + i];
        
        if (Math.abs(sourceValue - targetValue) > sampleTolerance) {
            mismatches.push({
                position: i,
                sourceValue,
                targetValue,
                difference: Math.abs(sourceValue - targetValue)
            });
            
            if (mismatches.length >= 10) break;
        }
    }
  
    // 返回验证结果
    if (mismatches.length === 0) {
        return {
            success: true,
            message: `数据成功写入，验证了 ${maxCheckLength} 个样本`,
            details: { checkedSamples: maxCheckLength }
        };
    } else {
        return {
            success: false,
            message: `写入验证失败，发现 ${mismatches.length} 处不匹配`,
            details: { mismatches }
        };
    }
  },
  copyToAudioChannel(audioBuffer, channelIndex, sourceArray, startInChannel = 0) {
    // 验证输入参数
    // if (!(audioBuffer instanceof AudioBuffer)) {
    //     throw new TypeError('第一个参数必须是AudioBuffer实例');
    // }
    
    if (typeof channelIndex !== 'number' || !Number.isInteger(channelIndex) || 
        channelIndex < 0 || channelIndex >= audioBuffer.numberOfChannels) {
        throw new RangeError(`无效的声道索引: ${channelIndex}`);
    }
    
    if (!(sourceArray instanceof Float32Array)) {
        throw new TypeError('源数据必须是Float32Array实例');
    }
    
    if (startInChannel < 0 || startInChannel >= audioBuffer.length) {
        throw new RangeError(`无效的起始位置: ${startInChannel}`);
    }
    
    // 计算可复制的最大长度
    const maxCopyLength = Math.min(
        sourceArray.length, 
        audioBuffer.length - startInChannel
    );
    
    if (maxCopyLength <= 0) {
        console.warn('没有可复制的数据');
        return 0;
    }
    
    // 使用copyToChannel复制数据
    audioBuffer.copyToChannel(sourceArray, channelIndex, startInChannel);
    
    return maxCopyLength;
  },
  choose1() {
    const audioCtx = wx.createWebAudioContext()
wx.request({
  url: 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3', // 音频 url
  responseType: 'arraybuffer',
  success: res => {
    audioCtx.decodeAudioData(res.data, audioBuffer => {
      const channels = audioBuffer.numberOfChannels;
      const frameCount = audioCtx.sampleRate * 2.0;
      const anotherArray = new Float32Array(frameCount);
      const rate = audioBuffer.sampleRate
      const startOffset = 0
      const endOffset = rate * 3;
      const newAudioBuffer = audioCtx.createBuffer(channels,endOffset - startOffset,rate)
      const offset = 0
      for (let channel = 0; channel < channels; channel++) {
        audioBuffer.copyFromChannel(anotherArray, channel, startOffset);
        console.log('copyFromChannel 成功')
        newAudioBuffer.copyToChannel(anotherArray, channel, offset);
        const myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
      const nowBuffering = myArrayBuffer.getChannelData(channel);
          this.setData({
          result: nowBuffering
        })
      }   
    }, err => {
      console.error('decodeAudioData fail', err)
    })
  }
})

    // const audioCtx = wx.createWebAudioContext()
    // wx.request({
    //   url: 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3', // 音频 url
    //   responseType: 'arraybuffer',
    //   success: res => {
    //     audioCtx.decodeAudioData(res.data, audioBuffer => {
    //       const channels = audioBuffer.numberOfChannels;
    //       const frameCount = audioCtx.sampleRate * 2.0;
    //       const anotherArray = new Float32Array(frameCount);
    //       const rate = audioBuffer.sampleRate
    //       const startOffset = 0
    //       const endOffset = rate * 3;
    //       const newAudioBuffer = audioCtx.createBuffer(channels,endOffset - startOffset,rate)
    //       const offset = 0
    //        // 2. 使用copyToChannel写入左声道（索引0）
    //     const writtenLength = this.copyToAudioChannel(audioBuffer, 0, anotherArray, 5000); // 从位置5000开始写入
    //     // 验证写入结果
    //     const writeVerification = this.verifyCopyToChannel(audioBuffer, 0, anotherArray, 5000);
    //     this.setData({
    //       result: writtenLength
    //     })
    //     console.log('写入验证结果:', writeVerification);    
    //     }, err => {
    //       console.error('decodeAudioData fail', err)
    //     })
    //   }
    // })
  },
})